﻿using Model;
using Service;
using System;
using System.Collections.Generic;
using System.Linq;
using Utility;

namespace DataProvider
{
    public class Sys_RoleProvider
    {
        public static readonly Sys_RoleProvider Instances = new Sys_RoleProvider();
        public static readonly Sys_RoleService Service = Sys_RoleService.Instances;

        public List<Sys_Role> GetList(RoleQuery queryModel, out int total)
        {
            var allList = Service.QueryCustom($" Status={(int)Status.normal}").ToList();

            var conditions = new List<Func<Sys_Role, bool>>();

            #region 组装查询
            if (!string.IsNullOrEmpty(queryModel.RoleName))
            {
                conditions.Add(x => x.RoleName != null && x.RoleName.Contains(queryModel.RoleName));
            }
            if (!string.IsNullOrEmpty(queryModel.RoleCode))
            {
                conditions.Add(x => x.RoleCode != null && x.RoleCode.Contains(queryModel.RoleCode));
            }
            if (!string.IsNullOrEmpty(queryModel.RoleName))
            {
                conditions.Add(x => x.Memo != null && x.Memo.Contains(queryModel.Memo));
            }
            #endregion

            foreach (var condition in conditions)
            {
                allList = allList.Where(condition).ToList();
            }

            if (queryModel.page>0 && queryModel.pageSize > 0)
            {
                allList= allList.Skip(queryModel.pageSize * (queryModel.page - 1)).Take(queryModel.pageSize).ToList();
            }

            total = allList.Count();

            return allList;
        }

        public Sys_Role Get(int id) => Service.GetEntity(id);

        public int SaveModel(int userId,Sys_Role model,out string errMsg)
        {
            var res = 0;
            errMsg = "";
            if (model.Id == 0)
            {
                res = Service.Add(userId, model);
            }
            else {
                res = Service.Edit(userId, model);
            }
            return res;
        }

        public int Del(int userId, int[] ids)
        {
            //删除角色相关的权限、用户。待定 #??

            return Service.EditBatch(userId,new Sys_Role() { Status = Status.delete, LastUpdateUser = userId, LastUpdateTime = DateTime.Now }, ids);
        }

    }
}
